package com.hd.trans.ui.base;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.TypedValue;
import android.view.View;

import com.hd.trans.framework.component.AtyGotoComponent;
import com.hd.trans.framework.component.DlgCancelCallback;
import com.hd.trans.framework.component.GotoComponent;
import com.hd.trans.framework.component.HuDunTimeoutCallback;
import com.hd.trans.framework.component.LoadingDlgComponent;
import com.hd.trans.framework.component.MyLoadingDlgComponent;
import com.hd.trans.framework.component.MyTimeOutComponent;
import com.hd.trans.framework.component.MyVaryViewComponent;
import com.hd.trans.framework.component.TimeOutComponent;
import com.hd.trans.framework.component.VaryViewComponent;
import com.hd.trans.framework.dialog.LoadingDialog;
import com.hd.trans.framework.interf.DoDelayedCallback;
import com.hd.trans.utils.PermissionUtil;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;


/**
 * Created by yang on 2016/9/8.
 */
public abstract class TransBaseActivity extends RxAppCompatActivity implements
        GotoComponent, TimeOutComponent, LoadingDlgComponent, VaryViewComponent { //,SnackbarEnable

    protected String TAG = getClass().getSimpleName();

    protected Bundle mSavedInstanceState;
    protected boolean isImmersion = true;


    private AtyGotoComponent mGotoComponent;
    private MyTimeOutComponent mTimeOutComponent;
    private MyLoadingDlgComponent mLoadingDlgComponent;
    private MyVaryViewComponent mVaryViewComponent;

    protected Handler mXHandler;
    protected PermissionUtil permissionUtil;




    /**
     * 传递过来的intent
     */
    protected Intent fromIntent;

    /**
     * (传递来的)准备数据是否正常
     */
    protected boolean prepareOk = true;


    /************************************************************************/

    /**
     * 界面layout ID
     */
    protected abstract int getLayoutId();

    /**
     * 初始化绑定View 工具(如:ButterKnife)
     */
    protected abstract void initBind();

    /**
     * 解绑 工具(如:ButterKnife)
     */
    protected abstract void unBind();


    /**
     * 是否在该页面注册 EventBus事件
     */
    protected boolean isBindEventBusHere() {
        return false;
    }

    /**
     * 是否忽略该页面自身发出来的 EventBus事件
     */
    protected boolean ignoreEventSelf() {
        return true;
    }

    /**
     * register EventBus
     */
    protected abstract void registerEventBus();

    /**
     * unregister EventBus
     */
    protected abstract void unregisterEventBus();


    /**
     * 初始化准备数据,返回准备结果(是否数据正常)
     */
    protected boolean initPrepareData() {
        return true;
    }


    /**
     * 用于处理一些基类设置通用ContentView
     */
    protected boolean usePrepareContentView() {
        return false;
    }

    /**
     * 初始化ContentView
     */
    protected void initPrepareContentView(Bundle savedInstanceState) {
    }

    /**
     * get loading target view(加载中,空数据,错误数据显示处---被替换的View)
     */
    protected View getVaryTargetView() {
        return null;
    }

    /**
     * 初始化View和事件
     */
    protected abstract void initViewsAndEvents(Bundle savedInstanceState);

    /**
     * 是否可以使用沉浸式
     */
    protected boolean immersionBarEnabled() {
        return true;
    }

    protected void initImmersionBar() {
//        ImmersionBar.with(this).init();
    }

    /************************************************************************/

    protected Class<?> getXClass() {
        return getClass();
    }

    protected TransBaseActivity getActivity() {
        return this;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        permissionUtil = new PermissionUtil(getSupportFragmentManager());
        if (mXHandler == null) {
            mXHandler = new Handler();
        }
        mGotoComponent = new AtyGotoComponent(this);
        mLoadingDlgComponent = new MyLoadingDlgComponent(this);
        mTimeOutComponent = new MyTimeOutComponent();

        mSavedInstanceState = savedInstanceState;
//        AppManager.getInstance().addActivity(this);
        if (isBindEventBusHere()) {
            registerEventBus();
        }
        int layoutId = getLayoutId();
        if (layoutId != 0) {
            fromIntent = getIntent();
            prepareOk = initPrepareData();
            if (usePrepareContentView()) {
                initPrepareContentView(savedInstanceState);
//                prepareContentView.addView(View.inflate(this, layoutId, null),
//                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            } else {
                setContentView(layoutId);
                initBind();
                if (getVaryTargetView() != null) {
                    mVaryViewComponent = new MyVaryViewComponent(getVaryTargetView());
                }

            }
//            if (prepareOk) {
                initViewsAndEvents(savedInstanceState);
            /*} else {
                Log.e(TAG, getString(R.string.err_data));
                ToastUtils.showError(R.string.err_data);
            }*/

        } else {
//            Log.e(TAG, getClass().getSimpleName() + " 页面 layout id 未设置");
//            ToastUtils.showError( getClass().getSimpleName() + " 页面 layout id 未设置" );
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        fromIntent = getIntent();
    }

    @Override
    protected void onStop() {
        //共享元素动画在Android10上异常的解决方案
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !isFinishing()) {
            Bundle bundle = new Bundle();
            bundle.putBoolean("InstrumentationFixBug",true);
            new Instrumentation().callActivityOnSaveInstanceState(this, bundle);
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mXHandler != null) {
            mXHandler.removeCallbacksAndMessages(null);
        }
        hideLoadDialog();
//        AppManager.getInstance().removeActivity(this);
        if (isBindEventBusHere()) {
            unregisterEventBus();
        }
        unBind();
        if (immersionBarEnabled()) {
//            ImmersionBar.with(this).destroy();
        }
    }


    /***************************************************超时处理***************************************************************/
    @Override
    public void startTimeoutThread(HuDunTimeoutCallback callback) {
        mTimeOutComponent.startTimeoutThread(callback);
    }

    @Override
    public void clearTimeoutThread() {
        mTimeOutComponent.clearTimeoutThread();
    }

    /***************************************************页面跳转***************************************************************/
    @Override
    public void gotoActivity(Class<? extends Activity> clz) {
        mGotoComponent.gotoActivity(clz);
    }

    @Override
    public void gotoActivity(Class<? extends Activity> clz, Bundle data) {
        mGotoComponent.gotoActivity(clz, data);
    }

    @Override
    public void gotoActivityForResult(Class<? extends Activity> clz, int requestCode) {
        mGotoComponent.gotoActivityForResult(clz, requestCode);
    }

    @Override
    public void gotoActivityForResult(Class<? extends Activity> clz, int requestCode, Bundle data) {
        mGotoComponent.gotoActivityForResult(clz, requestCode, data);
    }

    /***************************************************加载框***************************************************************/

    protected long mLastLoadingTime = 0;

    public LoadingDialog showLoadDialog() {
        return showLoadDialog(null, null);
    }

    public LoadingDialog showLoadDialog(int resId) {
        return showLoadDialog(resId, null, null);
    }

    public LoadingDialog showLoadDialog(String text) {
        return showLoadDialog(text, null, null);
    }

    @Override
    public LoadingDialog showLoadDialog(HuDunTimeoutCallback timeoutCallback, DlgCancelCallback cancelCallback) {
        mLastLoadingTime = SystemClock.elapsedRealtime();
        return mLoadingDlgComponent.showLoadDialog(timeoutCallback, cancelCallback);
    }

    @Override
    public LoadingDialog showLoadDialog(int resId, HuDunTimeoutCallback timeoutCallback, DlgCancelCallback cancelCallback) {
        mLastLoadingTime = SystemClock.elapsedRealtime();
        return mLoadingDlgComponent.showLoadDialog(resId, timeoutCallback, cancelCallback);
    }

    @Override
    public LoadingDialog showLoadDialog(String text, HuDunTimeoutCallback timeoutCallback, DlgCancelCallback cancelCallback) {
        mLastLoadingTime = SystemClock.elapsedRealtime();
        return mLoadingDlgComponent.showLoadDialog(text, timeoutCallback, cancelCallback);
    }

    @Override
    public void hideLoadDialog() {
        hideLoadDialog(true, null);
    }

    public void hideLoadDialog(boolean immediately, DoDelayedCallback doDelayedCallback) {
        long passTime = SystemClock.elapsedRealtime() - mLastLoadingTime;
        int delayed = Math.max(0, 1000 - (int) passTime);//保证加载动画有1000毫秒的时间
        if (delayed > 0 && mXHandler != null && !immediately) {
            mXHandler.postDelayed(() -> {
                mLoadingDlgComponent.hideLoadDialog();
                if (doDelayedCallback != null) {
                    doDelayedCallback.doDelayed();
                }
            }, delayed);
        } else {
            mLoadingDlgComponent.hideLoadDialog();
            if (!immediately && doDelayedCallback != null) {
                doDelayedCallback.doDelayed();
            }
        }
    }

    @Override
    public void setLoadingTips(String text) {
        runOnUiThread(() -> mLoadingDlgComponent.setLoadingTips(text));

    }

    /**************************************loading 、empty、error***********************************************/

    @Override
    public int getCurVaryViewState() {
        if (mVaryViewComponent != null) {
            return mVaryViewComponent.getCurVaryViewState();
        }
        return MyVaryViewComponent.STATE_SUCCESS;
    }

    @Override
    public void showLoading() {
        if (mVaryViewComponent != null)
            mVaryViewComponent.showLoading();
    }

    @Override
    public void showLoading(int resId) {
        if (mVaryViewComponent != null)
            mVaryViewComponent.showLoading(resId);
    }

    @Override
    public void showLoading(String msg) {
        if (mVaryViewComponent != null)
            mVaryViewComponent.showLoading(msg);

    }

    @Override
    public void showEmpty(String msg, View.OnClickListener onClickListener) {
        if (mVaryViewComponent != null)
            mVaryViewComponent.showEmpty(msg, onClickListener);
    }

    @Override
    public void showEmpty(String msg, int iconId, View.OnClickListener onClickListener) {
        if (mVaryViewComponent != null)
            mVaryViewComponent.showEmpty(msg, iconId, onClickListener);
    }

    @Override
    public void showEmptyCustom(int layoutId, int msgViewId, String msg, int clickViewId, final View.OnClickListener listener) {
        if (mVaryViewComponent != null)
            mVaryViewComponent.showEmptyCustom(layoutId, msgViewId, msg, clickViewId, listener);
    }

    @Override
    public void showError(String msg, View.OnClickListener onClickListener) {
        if (mVaryViewComponent != null)
            mVaryViewComponent.showError(msg, onClickListener);
    }

    @Override
    public void showError(String msg, int iconId, View.OnClickListener onClickListener) {
        if (mVaryViewComponent != null)
            mVaryViewComponent.showError(msg, iconId, onClickListener);
    }

    @Override
    public void showErrorCustom(int layoutId, int msgViewId, String msg, int clickViewId, final View.OnClickListener listener) {
        if (mVaryViewComponent != null)
            mVaryViewComponent.showErrorCustom(layoutId, msgViewId, msg, clickViewId, listener);
    }

    @Override
    public void showSuccess() {
        if (mVaryViewComponent != null)
            mVaryViewComponent.showSuccess();
    }

    /*********************************************************其它操作*********************************************************/

    protected View.OnLongClickListener mMenuItemLongClickListener = new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View view) {
            return true;
        }
    };

    protected int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

}
